<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>A页面</title>
  </head>
  <body>
    <p>A页面接收B页面通过postMessage发送的消息：</p>
    <h4 id="content"></h4>
    <iframe id="iframe" src="http://localhost:8081/postMessageB.html"></iframe>
    <script>
      const iframe = document.getElementById("iframe");
      const content = document.getElementById("content");
      const popup = iframe.contentWindow;
      const toOrigin = "http://localhost:8081";
      window.onload = function () {
        popup.postMessage("A发送来的信息", toOrigin);
      };

      function receiveMessage(event) {
        console.log("A页面", event);
        if (event.origin !== toOrigin) {
          return;
        }
        content.innerText = event.data;
      }

      window.addEventListener("message", receiveMessage, false);
    </script>
  </body>
</html>
